package com.jackrain.nea.fc.vp.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.PostHandleEvent;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.ChrusersWebQueryCmd;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.vp.api.CvipSearchCmd;
import com.jackrain.nea.fc.vp.api.ViewCretailftpAddCmd;
import com.jackrain.nea.fc.vp.mapper.ViewCretailftpMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.QueryCmd;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @author wuwenxue
 * @date 2017/11/13
 **/
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "vp")
public class ViewCretailftpAddCmdImpl extends CommandAdapter implements ViewCretailftpAddCmd {

    @Reference(version = "2", group = "cp")
    private QueryCmd queryCmd;

    @Reference(version = "1.0", group = "cp")
    private ChrusersWebQueryCmd chrusersWebQueryCmd;

    @Reference(version = "1.0", group = "vp")
    private CvipSearchCmd cvipSearchCmd;

    @Autowired
    PostHandleEvent postHandleEvent;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

//        log.info("<==============调用会员消费流水==============>");

        ViewCretailftpMapper viewCretailftpMapper = ApplicationContextHandle.getBean(ViewCretailftpMapper.class);
        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"),
                "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("ViewCretailftpAddCmdImpl--param-->{}",param);

        if ((null == param) || (!param.containsKey("data")) || param.getJSONArray("data").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }

        JSONArray jsonArray = param.getJSONArray("data");

        if (jsonArray.size() > 100) {
            throw new NDSException("POS端数据过大，无法处理！");
        }

        User user = chrusersWebQueryCmd.getUser("INTER99999");
        QuerySessionImpl querySession = new QuerySessionImpl(user);
        DefaultWebEvent event = new DefaultWebEvent("test", new HashMap(16));

//        log.info("POS端数据：" + jsonArray.toString());
        JSONArray jsArray = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            //VIP类型
            Long vipTypeGroup = viewCretailftpMapper.vipType(jsonObject.getString("VP_C_VIPTYPEGROUP_ID"));

            //查询VIP档案ID
            JSONObject vipSearchJson = new JSONObject();
            //fixedcolumns
            JSONObject fixedcolumnsJson = new JSONObject();
            fixedcolumnsJson.put("ACC.ECODES", jsonObject.getString("VP_C_VIP_ID"));
            fixedcolumnsJson.put("ACC.VP_C_VIPTYPEGROUP_ID", vipTypeGroup);
            // orderByArray = new JSONArray();
            //searchtype
            JSONArray searchTypeArray = new JSONArray();
            JSONObject ecodeName = new JSONObject();
            ecodeName.put("name", "ACC.ECODES");
            ecodeName.put("type", "exact");
            searchTypeArray.add(ecodeName);
            JSONObject vipTypeName = new JSONObject();
            vipTypeName.put("name", "ACC.VP_C_VIPTYPEGROUP_ID");
            vipTypeName.put("type", "exact");
            searchTypeArray.add(vipTypeName);

            vipSearchJson.put("fixedcolumns", fixedcolumnsJson);
            vipSearchJson.put("searchtype", searchTypeArray);

            event.put("param", vipSearchJson);
            querySession.setEvent(event);
            ValueHolder vipValue = cvipSearchCmd.execute(querySession);
            JSONObject vipJson = vipValue.toJSONObject();
//            log.info("vipJson:" + vipJson);
            if (null == vipJson || (!vipJson.containsKey("IDS"))) {
                throw new NDSException("未查询到VIPID   " + vipJson);
            }

            JSONArray idsArray = vipJson.getJSONArray("IDS");
            if (idsArray.size() != 1) {
                throw new NDSException("IDS未查询到或存在多条   IDS.SIZE:" + idsArray.size());
            }

            Long vipID = idsArray.getLong(0);

            //VIP卡号 VP_C_VIP_ID
            //Long vipID = viewCretailftpMapper.vipID(jsonObject.getString("VP_C_VIP_ID"), vipTypeGroup);

            //店仓 【跨库】
            HashMap storeHashMap = new HashMap(16);
            storeHashMap.put("type", HashMap.class);
            storeHashMap.put("tableName", "CP_C_STORE");
            storeHashMap.put("fields", "ID,CP_C_DISTRIB_ID");
            JSONObject whereJsonToStore = new JSONObject();
            whereJsonToStore.put("ECODE", jsonObject.getString("CP_C_STORE_ID"));
            storeHashMap.put("whereKeys", whereJsonToStore);
            //Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(),
            // "com.jackrain.nea.web.QueryCmd", "cp", "2");
            HashMap cpStore = (HashMap) queryCmd.queryTable(storeHashMap);

            if (null == cpStore || (!cpStore.containsKey("ID")) || (!cpStore.containsKey("CP_C_DISTRIB_ID"))) {
//                log.info("CP_C_STORE_ID==>" + jsonObject.getString("CP_C_STORE_ID"));
//                log.info("cpStore:" + cpStore);
                throw new NDSException("该店仓数据错误！  cpStore:" + cpStore);
            }

            Long storeID = (Long) cpStore.get("ID");
            Long storeDistrib = (Long) cpStore.get("CP_C_DISTRIB_ID");

            //【跨库】
            HashMap skuHashMap = new HashMap(16);
            skuHashMap.put("type", HashMap.class);
            skuHashMap.put("tableName", "PS_C_SKU");
            skuHashMap.put("fields", "ID,PS_C_PRO_ID");
            JSONObject whereJsonToSku = new JSONObject();
            whereJsonToSku.put("ECODE", jsonObject.getString("PS_C_SKU_ID"));
            whereJsonToSku.put("CP_C_DISTRIB_ID", storeDistrib);
            skuHashMap.put("whereKeys", whereJsonToSku);
            HashMap cpSku = (HashMap) queryCmd.queryTable(skuHashMap);

            if (null == cpSku || (!cpSku.containsKey("ID")) || (!cpSku.containsKey("PS_C_PRO_ID"))) {
                throw new NDSException("sku数据存在错误！" + "    SKU_HashMap:" + cpSku + "   店仓配销中心:" + storeDistrib);
            }

            //SKU
            Long skuID = (Long) cpSku.get("ID");
            //商品
            Long proID = (Long) cpSku.get("PS_C_PRO_ID");

            /*//跨库查询USERS
            HashMap hashMap = new HashMap(16);
            hashMap.put("tableName", "USERS");
            hashMap.put("fields", "ID,ENAME");
            hashMap.put("type", HashMap.class);
            JSONObject whereJson = new JSONObject();
            whereJson.put("NAME", "INTER99999");
            hashMap.put("whereKeys", whereJson);
            HashMap cpJS = (HashMap) queryCmd.queryTable(hashMap);

            //固定传输用户编号：INTER99999
            if (null == cpJS || (!cpJS.containsKey("ID")) || (!cpJS.containsKey("ENAME"))) {
                throw new NDSException("INTER99999用户错误！");
            }
            Long user = (Long) cpJS.get("ID");
            String ename = (String) cpJS.get("ENAME");*/

            //吊牌金额
            BigDecimal amt = null;
            if (jsonObject.containsKey("PRICE") && jsonObject.containsKey("QTYBILL")) {
                amt = jsonObject.getBigDecimal("PRICE").multiply(jsonObject.
                        getBigDecimal("QTYBILL"));
            }

            //成交价
            BigDecimal priceActualm = null;
            if (jsonObject.containsKey("AMT_ACTUAL") && jsonObject.containsKey("QTYBILL") &&
                    (jsonObject.getBigDecimal("QTYBILL").compareTo(BigDecimal.ZERO) != 0)) {
                priceActualm = jsonObject.getBigDecimal("AMT_ACTUAL").divide(
                        jsonObject.getBigDecimal("QTYBILL"), 2, RoundingMode.HALF_UP);
            }

            Long date = null;
            if (null != jsonObject.getString("BILLDATE")) {
                Date d = TypeUtils.castToDate(jsonObject.getString("BILLDATE"));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                String newDate = simpleDateFormat.format(d);
                date = TypeUtils.castToLong(newDate);
            }

            JSONObject jsObj = new JSONObject();

            jsObj.put("sourceId", jsonObject.getString("sourceId"));
            jsObj.put("VP_C_VIP_ID", vipID);
            jsObj.put("VP_C_VIPTYPEGROUP_ID", vipTypeGroup);
            jsObj.put("DOCNO", jsonObject.getString("DOCNO"));
            jsObj.put("BILLDATE", date);
            jsObj.put("CP_C_STORE_ID", storeID);
            jsObj.put("PS_C_SKU_ID", skuID);
            jsObj.put("PS_C_PRO_ID", proID);
            //吊牌价
            jsObj.put("PRICE", jsonObject.getBigDecimal("PRICE"));
            //结算价
            jsObj.put("PRICEACC", jsonObject.getBigDecimal("PRICEACC"));
            //成交价
            jsObj.put("PRICEACTUAL", priceActualm);
            jsObj.put("QTYBILL", jsonObject.getBigDecimal("QTYBILL"));
            jsObj.put("AMT", amt);
            jsObj.put("AMT_ACTUAL", jsonObject.getBigDecimal("AMT_ACTUAL"));
            jsObj.put("REMARK", jsonObject.getString("REMARK"));
            //jsObj.put("OWNERID", user);
            jsObj.put("CREATIONDATE", jsonObject.getString("BILLDATE"));
            //jsObj.put("MODIFIERID", user);
            jsObj.put("MODIFIEDDATE", jsonObject.getString("BILLDATE"));
            /*jsObj.put("AD_CLIENT_ID", 37);
            jsObj.put("AD_ORG_ID", 27);
            jsObj.put("ID", Tools.getSequence("VP_C_VIP_RETAILFTP"));
            jsObj.put("MODIFIERNAME", "INTER99999");
            jsObj.put("MODIFIERENAME", ename);
            jsObj.put("OWNERNAME", "INTER99999");
            jsObj.put("OWNERENAME", ename);*/
            //结算金额
            jsObj.put("AMT_ACC", jsonObject.getBigDecimal("AMT_ACC"));
            //折扣
            jsObj.put("DISCOUNT", jsonObject.getBigDecimal("DISCOUNT"));
            //积分
            jsObj.put("INTE", jsonObject.getBigDecimal("INTE"));

            jsArray.add(jsObj);

        }

        JSONObject retailftpObj = new JSONObject();
        retailftpObj.put("data", jsArray);
        retailftpObj.put("table", "VP_C_VIP_RETAILFTP");
//        log.info("翻译后数据：" + retailftpObj.toString());
        log.debug("ViewCretailftpAddCmdImpl--retailftpObj-->{}",retailftpObj.toString());

        event.put("param", retailftpObj);
        event.put("forward", "com.jackrain.nea.vp.api.CvipretailftpAddCmd");
        querySession.setEvent(event);
        //Object o1 = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(),
        // "com.jackrain.nea.vp.api.CvipretailftpAddCmd", "vp", "1.0");
//        vh = cvipretailftpAddCmd.execute(querySession);

        // 变更为handle调用--WSL
        try {

            //TODO
            JSONObject jo = postHandleEvent.executePostHandle(retailftpObj, querySession, event, "add");

            if (null != jo) {
                vh.put("code", jo.get("code"));
                vh.put("message", jo.getString("message"));
            }

//            vh = handle.process(retailftpObj, querySession, event, "add");
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
//            log.error(sw.toString());
            log.error("ViewCretailftpAddCmdImpl--error-->{}",sw.toString());

        }

        JSONObject vipRetailftJson = vh.toJSONObject();
        if (vipRetailftJson.containsKey("code") && (vipRetailftJson.getLong("code") == -1)) {
            throw new NDSException("调用标准服务错误:" + vipRetailftJson.getString("message"));
        }

        return vh;
    }


}
